package cn.antho.product.service.impl;

import cn.antho.basic.config.BussinessException;
import cn.antho.basic.util.CodeGenerateUtils;
import cn.antho.basic.util.DelayMessageUtil;
import cn.antho.basic.util.LoginContext;
import cn.antho.basic.util.PageList;
import cn.antho.order.domain.OrderProduct;
import cn.antho.order.mapper.OrderProductMapper;
import cn.antho.org.domain.Employee;
import cn.antho.org.mapper.EmployeeMapper;
import cn.antho.product.domain.Product;
import cn.antho.product.domain.ProductOrderMsg;
import cn.antho.product.dto.PrepareOrderDto;
import cn.antho.product.mapper.ProductMapper;
import cn.antho.product.mapper.ProductOrderMsgMapper;
import cn.antho.product.query.ProductOrderMsgQuery;
import cn.antho.product.service.IProductOrderMsgService;
import cn.antho.basic.service.impl.BaseServiceImpl;
import cn.antho.user.domain.Logininfo;
import cn.antho.user.domain.User;
import cn.antho.user.mapper.UserMapper;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author antho
 * @since 2022-11-03
 */
@Service
public class ProductOrderMsgServiceImpl extends BaseServiceImpl<ProductOrderMsg> implements IProductOrderMsgService {

    @Autowired
    private ProductOrderMsgMapper productOrderMsgMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;

    @Override
    public void prepareOrder(Long id, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        Product product = productMapper.findById(id);
        ProductOrderMsg productOrderMsg = new ProductOrderMsg();
        productOrderMsg.setName(product.getName());
        productOrderMsg.setProductId(product.getId());
        productOrderMsg.setState(0);
        productOrderMsg.setShopId(product.getShopId());
        productOrderMsg.setSaleprice(product.getSaleprice());
        productOrderMsg.setCostprice(product.getCostprice());
        productOrderMsg.setCreatetime(new Date());
        productOrderMsg.setUserId(user.getId());
        productOrderMsgMapper.add(productOrderMsg);
        try {
            DelayMessageUtil.producer("product_order_group",
                    "product_order_topic",
                    "product_order_tag",
                    productOrderMsg.getId()+"",
                    4);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void accept(PrepareOrderDto dto) {
        // 根据id查询到服务消息
        ProductOrderMsg productOrderMsg = productOrderMsgMapper.findById(dto.getMsgId());
        System.out.println(productOrderMsg);

        // 校验服务消息是否为空
        if (null == productOrderMsg) {
            throw new BussinessException("服务消息为空！");
        }
        // 解决线程安全问题
        synchronized (productOrderMsg.getId()) {
            // 判断员工是否为空
            Employee employee = employeeMapper.findById(dto.getHandler());
            if (null == employee) {
                throw new BussinessException("员工为空！请校验！");
            }
            // 判断寻主消息状态 校验寻主消息中店铺id与员工shopId
            if (0 == productOrderMsg.getState() && productOrderMsg.getShopId().equals(employee.getShopId())) {
                // 修改寻主消息状态
                productOrderMsg.setState(1);
                productOrderMsgMapper.update(productOrderMsg);
            }
            // 生成订单
            initOrder(dto, productOrderMsg, employee);
        }
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        ProductOrderMsg orderMsg = productOrderMsgMapper.findById(id);
        orderMsg.setState(-1);
        productOrderMsgMapper.update(orderMsg);
    }

    @Override
    public PageList<ProductOrderMsg> queryByState(ProductOrderMsgQuery query) {
        // 查询条数
        Integer totals = productOrderMsgMapper.queryByCount(query);
        if (null == totals || 0 == totals){
            return new PageList<>(0, new ArrayList<>());
        }
        // 查询数据
        List<ProductOrderMsg> ts = productOrderMsgMapper.queryByState(query);
        // 放到返回里面
        return new PageList<>(totals, ts);
    }

    /**
     * 生成订单方法
     * @param dto
     * @param productOrderMsg
     * @param employee
     */
    private void initOrder(PrepareOrderDto dto, ProductOrderMsg productOrderMsg, Employee employee) {
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        String digest = "[服务订单]购买1次" + productMapper.findById(productOrderMsg.getProductId()).getName() + "服务！";
        orderProduct.setDigest(digest);
        orderProduct.setLastPayTime(new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
        orderProduct.setState(0);
        orderProduct.setUserId(productOrderMsg.getUserId());
        orderProduct.setShopId(employee.getShopId());
        orderProduct.setProductId(productOrderMsg.getProductId());
        orderProduct.setProductOrderMsgId(productOrderMsg.getId());
        orderProductMapper.add(orderProduct);
        try {
            DelayMessageUtil.producer("product_order_group",
                    "product_order_topic",
                    "product_order_tag",
                    orderProduct.getId()+"",
                    4);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
